<template>
  <view class="trend-container">
    <!-- 筛选栏 -->
    <view class="filter-bar">
      <UpChoose
        v-model="dateRange"
        item-width="220rpx"
        item-height="80rpx"
        :options="options"
        :custom-click="false"
        @change="onDeliveryTimeChange"
      />
      <view class="batch-search">
        <u-input
          v-model="batchNumber"
          type="number"
          placeholder="混合批次"
          class="batch-input"
        />
        <up-button type="primary" @click="searchBatch">
          搜索
        </up-button>
      </view>
    </view>

    <!-- 图表区域 -->
    <view class="chart-container">
      <view class="chart-header">
        <text class="chart-title">
          含水率趋势
        </text>
        <u-icon name="刷新" class="refresh-icon" @click="refreshChart" />
      </view>
      <view class="chart-wrapper">
        <qiun-data-charts
          type="area"
          :chart-data="chartData"
          :width="chartWidth"
          :height="chartHeight"
          :pixel-ratio="pixelRatio"
          :opts="chartOptions"
          :canvas2d="true"
          canvas-id="kVEckwIhMHvhhzSvZjtTzFIdedWkKITC"
        />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import type { MoistureStatisticReq } from '@/api/moisture/types';
import { computed, onMounted, ref } from 'vue';
import { getMoistureStatistic } from '@/api/moisture';
import UpChoose from '@/components/up-choose/index.vue';
import { usePermission } from '@/hooks';
// 日期范围选项
const options = ref([
  { id: 'week', title: '本周' },
  { id: 'month', title: '本月' },
  { id: 'quarter', title: '近三月' },
]);

const startTime = ref('');
const endTime = ref('');

// 筛选条件
// const selectedFeedType = ref('');
// const selectedBatchNumber = ref('');
const dateRange = ref(0); // 默认选择本周
const batchNumber = ref(1);

// 图表配置
const chartWidth = ref(0);
const chartHeight = ref(300);
const pixelRatio = ref(1);
const chartData = ref<any>({
  categories: [],
  series: [],
});

// 统计数据
// const avgMoisture = ref('0.0');
// const maxMoisture = ref('0.0');
// const minMoisture = ref('0.0');

// 图表配置选项
const chartOptions = ref({
  color: ['#1890FF', '#91CB74', '#FAC858', '#EE6666', '#73C0DE', '#3CA272', '#FC8452', '#9A60B4', '#ea7ccc'],
  padding: [15, 15, 0, 15],
  enableScroll: true,
  legend: {},
  xAxis: {
    disableGrid: true,
    itemCount: 10,
  },
  yAxis: {
    gridType: 'dash',
    dashLength: 2,
  },
  extra: {
    area: {
      type: 'curve',
      opacity: 0.2,
      addLine: true,
      width: 2,
      gradient: true,
      activeType: 'hollow',
    },
  },
});

// 批次搜索函数
function searchBatch() {
  if (batchNumber.value) {
    getMoistureStatisticData();
  }
}

function getMoistureStatisticData() {
  const params: MoistureStatisticReq = {
    startTime: startTime.value,
    endTime: endTime.value,
    statisticsType: 'day',
    batchNumber: batchNumber.value.toString(),
  };
  getMoistureStatistic(params).then((res) => {
    if (res.code === '200') {
      const data = res.data;
      chartData.value = data;
    }
  });
}

// 刷新图表
function refreshChart() {
  getMoistureStatisticData();
}

computed(() => {
  // 计算图表标题
  console.log('计算图表标题:', options.value[dateRange.value].title);
  return options.value[dateRange.value].title;
});

// 日期范围变化处理
function onDeliveryTimeChange(index: number) {
  console.log('日期范围变化:', index, options.value[index].id);
  dateRange.value = index;
  // 处理开始日期和结束日期
  const currentDate = new Date();
  const endDate = new Date(currentDate);
  const startDate = new Date(currentDate);
  if (dateRange.value === 0) {
    // 本周
    endDate.setDate(currentDate.getDate());
    startDate.setDate(currentDate.getDate() - 6);
  }
  else if (dateRange.value === 1) {
    // 本月
    endDate.setDate(currentDate.getDate());
    startDate.setMonth(currentDate.getMonth() - 1);
  }
  else if (dateRange.value === 2) {
    // 近三月
    endDate.setDate(currentDate.getDate());
    startDate.setMonth(currentDate.getMonth() - 3);
  }
  startTime.value = `${startDate.toISOString().split('T')[0]} 00:00:00`;
  endTime.value = `${endDate.toISOString().split('T')[0]} 23:59:59`;

  console.log('日期范围变化:', startTime.value, endTime.value);
  getMoistureStatisticData();
}

// 页面加载时初始化
onMounted(() => {
  // 设置图表宽度为屏幕宽度减去边距
  const sysInfo = uni.getSystemInfoSync();
  chartWidth.value = sysInfo.windowWidth - 60; // 左右各30rpx边距
  pixelRatio.value = sysInfo.pixelRatio;
  onDeliveryTimeChange(dateRange.value);

  // 初始化图表数据
  chartData.value = {
    categories: [],
    series: [],
  };

  getMoistureStatisticData();
});

// 登录鉴权，微信小程序端点击tabbar的底层逻辑不触发uni.switchTab，需要在页面onShow生命周期中校验权限
onShow(async () => {
  const hasPermission = await usePermission();
  console.log(hasPermission ? '已登录' : '未登录，拦截跳转');
});
</script>

<style scoped lang="scss">
.trend-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 88rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #eeeeee;
}

.title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

.filter-bar {
  display: flex;
  padding: 20rpx;
  background-color: #ffffff;
  border-bottom: 1rpx solid #f0f0f0;
  flex-wrap: wrap;
}
.batch-search {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 20rpx;
  padding: 10rpx 0;
}
.search-btn{
  height: 60rpx;
  line-height: 40rpx;
  padding: 0 20rpx;
  border-radius: 8rpx;
  background-color: #07c160;
  color: #ffffff;
  font-size: 28rpx;
  font-weight: 600;
}

.filter-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 10rpx 0;
  border-right: 1rpx solid #f0f0f0;
}

.filter-item:last-child {
  border-right: none;
}

.filter-label {
  font-size: 24rpx;
  color: #999999;
  margin-bottom: 4rpx;
}

.filter-value {
  font-size: 28rpx;
  color: #333333;
}

.filter-item {
  cursor: pointer;
}

.filter-item:active {
  background-color: #f5f5f5;
}

.filter-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  cursor: pointer;
}

.filter-label {
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 8rpx;
}

.filter-value {
  font-size: 28rpx;
  color: #333333;
  font-weight: 500;
}

.chart-container {
  margin: 20rpx;
  padding: 20rpx;
  background-color: #ffffff;
  border-radius: 10rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.chart-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333333;
}

.refresh-icon {
  font-size: 28rpx;
  color: #07c160;
}

.chart-wrapper {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.stats-cards {
  display: flex;
  padding: 0 20rpx 20rpx;
  gap: 20rpx;
}

.stat-card {
  flex: 1;
  padding: 20rpx;
  background-color: #ffffff;
  border-radius: 10rpx;
  text-align: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.stat-label {
  display: block;
  font-size: 24rpx;
  color: #666666;
  margin-bottom: 10rpx;
}

.stat-value {
  display: block;
  font-size: 36rpx;
  font-weight: 600;
  color: #07c160;
}
</style>
